<template>
  <div class="up-file">
    <srcElUpload
      ref="srcElUpload"
      class="upload-demo"
      action=""
      :http-request="httpRequest"
      multiple
      :limit="limit"
      :on-exceed="onExceed"
      :accept="getAccept"
      :before-upload="beforeUpload"
      :on-change="onChange"
      :on-remove="onChange"
      :file-list="fileList"
      :on-preview="previewDownFile">
      <el-button size="small" type="primary" :disabled="limit<=nowLimit">
        上传文件
      </el-button>
    </srcElUpload>
  </div>
</template>

<script>
import srcElUpload from './src/index.vue'

import {deepCopy} from '@/utils/tools/tools'
import {uploadFile} from '@/depends/api/file'
import {downFile} from '@/utils/tools/tools'

export default {
  name: 'UpFile',
  components: {
    srcElUpload
  },
  props: {
    limit: '',
    accept: {
      type: Array,
      default: () => []
    },
    fileListS: {
      type: Array,
      default: () => []
    }
  },
  data() {  
    return {
      headers: {
        sessionId: localStorage.sessionId,
      },
      apiURL: window.SITE_CONFIG.apiURL,
      nowLimit: 0,
      fileList: []
    };
  },
  computed:{
    getAccept () {
      return this.accept.join(',')
    }
  },
  created() {
    this.fileList = deepCopy(this.fileListS)
    this.nowLimit = this.fileList.length
  },
  mounted () {
  },
  methods: {
    beforeUpload (a) {
      if (!this.accept.length) { return true }
      let istrueAccept = this.accept.includes(a.name.substring(a.name.lastIndexOf("."), a.name.length).toLowerCase())
      if (istrueAccept) {
        return true
      }else {
        this.$message.error(`请上传${this.getAccept}格式文件!`)
        return false
      }

    },
    onChange (file, fileList) {
      if (file.raw&&!file.response) {
        return
      }
      this.nowLimit = fileList.length
      this.$emit('onChange', fileList.map(a => {
        if (a.response) {
          return { name: a.response.name, url: a.response.url}
        } else {
          return { name: a.name, url: a.url }
        }
      }))
    },
    httpRequest (e) {
      let form = new FormData();
      form.append("file", e.file)
      uploadFile(form, (progress) => {
      }).then(res => {
        e.onSuccess({name: e.file.name, url: res.data.data})
      }).catch(err => {
        e.onError(err)
      })
    },
    onExceed (files, fileList) {
      this.$message.error(`当前限制选择 ${this.limit} 个文件!`);
    },
    previewDownFile (file) {
      let url = ''
      if (file.response && file.response.url) { url = file.response.url }
      if (file.url) { url = file.url }
      downFile(url)
    }
  }
};
</script>

<style lang="less" scoped>
</style>
<style lang="less">
.up-file {
  .elprogress {
    .el-progress-bar__outer {
      height: 2px !important;
    }
  }
}
</style>
